/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package database.entitymanager;

import database.entity.UserGroup;
import database.entitymanager.exceptions.IllegalOrphanException;
import database.entitymanager.exceptions.NonexistentEntityException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import database.entity.User;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Stefan
 */
public class UserGroupManager {

    private static EntityManagerFactory emf = EntityFactoryHolder.getInstance();

    public static EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public static void create(UserGroup userGroup) {
        if (userGroup.getUserList() == null) {
            userGroup.setUserList(new ArrayList<User>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<User> attachedUserList = new ArrayList<User>();
            for (User userListUserToAttach : userGroup.getUserList()) {
                userListUserToAttach = em.getReference(userListUserToAttach.getClass(), userListUserToAttach.getUserid());
                attachedUserList.add(userListUserToAttach);
            }
            userGroup.setUserList(attachedUserList);
            em.persist(userGroup);
            for (User userListUser : userGroup.getUserList()) {
                UserGroup oldUserGroupOfUserListUser = userListUser.getUserGroup();
                userListUser.setUserGroup(userGroup);
                userListUser = em.merge(userListUser);
                if (oldUserGroupOfUserListUser != null) {
                    oldUserGroupOfUserListUser.getUserList().remove(userListUser);
                    oldUserGroupOfUserListUser = em.merge(oldUserGroupOfUserListUser);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static void edit(UserGroup userGroup) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            UserGroup persistentUserGroup = em.find(UserGroup.class, userGroup.getUgid());
            List<User> userListOld = persistentUserGroup.getUserList();
            List<User> userListNew = userGroup.getUserList();
            List<String> illegalOrphanMessages = null;
            for (User userListOldUser : userListOld) {
                if (!userListNew.contains(userListOldUser)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain User " + userListOldUser + " since its userGroup field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<User> attachedUserListNew = new ArrayList<User>();
            for (User userListNewUserToAttach : userListNew) {
                userListNewUserToAttach = em.getReference(userListNewUserToAttach.getClass(), userListNewUserToAttach.getUserid());
                attachedUserListNew.add(userListNewUserToAttach);
            }
            userListNew = attachedUserListNew;
            userGroup.setUserList(userListNew);
            userGroup = em.merge(userGroup);
            for (User userListNewUser : userListNew) {
                if (!userListOld.contains(userListNewUser)) {
                    UserGroup oldUserGroupOfUserListNewUser = userListNewUser.getUserGroup();
                    userListNewUser.setUserGroup(userGroup);
                    userListNewUser = em.merge(userListNewUser);
                    if (oldUserGroupOfUserListNewUser != null && !oldUserGroupOfUserListNewUser.equals(userGroup)) {
                        oldUserGroupOfUserListNewUser.getUserList().remove(userListNewUser);
                        oldUserGroupOfUserListNewUser = em.merge(oldUserGroupOfUserListNewUser);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = userGroup.getUgid();
                if (findUserGroup(id) == null) {
                    throw new NonexistentEntityException("The userGroup with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            UserGroup userGroup;
            try {
                userGroup = em.getReference(UserGroup.class, id);
                userGroup.getUgid();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The userGroup with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<User> userListOrphanCheck = userGroup.getUserList();
            for (User userListOrphanCheckUser : userListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This UserGroup (" + userGroup + ") cannot be destroyed since the User " + userListOrphanCheckUser + " in its userList field has a non-nullable userGroup field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(userGroup);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public static List<UserGroup> findUserGroupEntities() {
        return findUserGroupEntities(true, -1, -1);
    }

    public static List<UserGroup> findUserGroupEntities(int maxResults, int firstResult) {
        return findUserGroupEntities(false, maxResults, firstResult);
    }

    private static List<UserGroup> findUserGroupEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(UserGroup.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public static UserGroup findUserGroup(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(UserGroup.class, id);
        } finally {
            em.close();
        }
    }

    public static int getUserGroupCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<UserGroup> rt = cq.from(UserGroup.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
